/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Registros;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import utilitarios.conexion;
/**
 *
 * @author Miguel Recalde
 */
public class registro_barrio extends javax.swing.JFrame {

    /**
     * Creates new form registro_ciudad
     */
    int btn_clicado = 0; //variable que almacena cul boton fue clicado
    conexion conecta_barrio;// Conexion con BD
    int inicia_cbBuscar =0;//variable que utilizo para buscar en el CB
    String ordenar = "nombre";//Variable que sera pasada por parametro
    public registro_barrio() 
    {
        initComponents();
        conecta_barrio = new conexion();
        conecta_barrio.conectar();
        conecta_barrio.executeSQL("select * from barrio order by codigo");
       
             
        try
        {
             while(conecta_barrio.resulset.next())//codigo buscar Combo BOX
              {
                  cb_buscar.addItem(conecta_barrio.resulset.getString("nombre"));
              }
            
            conecta_barrio.resulset.first();
            tf_codigo.setText(conecta_barrio.resulset.getString("codigo"));
            tf_nombre.setText(conecta_barrio.resulset.getString("nombre"));
          
            
        }
        catch (SQLException erro)
           {
                JOptionPane.showMessageDialog(null,"No hay datos "+erro);
           }
        
          actualizaJtable();// llama el metodo para llenar la tabla
        
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenu2 = new javax.swing.JMenu();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        bg_ordenar = new javax.swing.ButtonGroup();
        jLabel1 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        tf_buscar = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        cb_buscar = new javax.swing.JComboBox();
        btn_buscar = new java.awt.Button();
        btn_buscarC = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        tf_codigo = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        tf_nombre = new javax.swing.JTextField();
        jPanel3 = new javax.swing.JPanel();
        btn_primero = new javax.swing.JButton();
        btn_anterior = new javax.swing.JButton();
        btn_siguiente = new javax.swing.JButton();
        btn_ultimo = new javax.swing.JButton();
        btn_grabar = new javax.swing.JButton();
        btn_nuevo = new javax.swing.JButton();
        btn_modificar = new javax.swing.JButton();
        btn_borrar = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        Tabla = new javax.swing.JTable();
        jPanel4 = new javax.swing.JPanel();
        rb_codigo = new javax.swing.JRadioButton();
        rb_Nombre = new javax.swing.JRadioButton();
        jButton2 = new javax.swing.JButton();

        jMenu1.setText("File");
        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");
        jMenuBar1.add(jMenu2);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Registro de Ciudades");
        setPreferredSize(new java.awt.Dimension(800, 600));

        jLabel1.setFont(new java.awt.Font("Arial", 0, 18)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(0, 0, 204));
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Registro de Barrio");

        jPanel1.setBackground(new java.awt.Color(239, 205, 205));

        tf_buscar.setToolTipText("Digite las iniciales de las ciudades para localizarlas ");

        jLabel5.setText("Buscar:");

        cb_buscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cb_buscarActionPerformed(evt);
            }
        });

        btn_buscar.setLabel("Buscar");
        btn_buscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_buscarActionPerformed(evt);
            }
        });

        btn_buscarC.setText("Buscar");
        btn_buscarC.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_buscarCActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(cb_buscar, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tf_buscar, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btn_buscar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btn_buscarC))
                .addContainerGap(18, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(4, 4, 4)
                        .addComponent(tf_buscar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(btn_buscar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btn_buscarC)
                    .addComponent(cb_buscar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.setBackground(new java.awt.Color(255, 204, 204));
        jPanel2.setForeground(new java.awt.Color(0, 204, 204));

        jLabel2.setText("Codigo:");

        jLabel3.setText("Nombre:");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING))
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(tf_nombre, javax.swing.GroupLayout.PREFERRED_SIZE, 202, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tf_codigo, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(45, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tf_codigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tf_nombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel3.setBackground(new java.awt.Color(0, 153, 0));

        btn_primero.setText("<<");
        btn_primero.setToolTipText("Lleva al primer registro");
        btn_primero.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_primeroActionPerformed(evt);
            }
        });

        btn_anterior.setText("<");
        btn_anterior.setToolTipText("Lleva al registro anterior");
        btn_anterior.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_anteriorActionPerformed(evt);
            }
        });

        btn_siguiente.setText(">");
        btn_siguiente.setToolTipText("Siguiente Registro");
        btn_siguiente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_siguienteActionPerformed(evt);
            }
        });

        btn_ultimo.setText(">>");
        btn_ultimo.setToolTipText("Último Registro");
        btn_ultimo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_ultimoActionPerformed(evt);
            }
        });

        btn_grabar.setText("Grabar");
        btn_grabar.setToolTipText("Grabar un registro");
        btn_grabar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_grabarActionPerformed(evt);
            }
        });

        btn_nuevo.setText("Nuevo");
        btn_nuevo.setToolTipText("Agregar nuevo registro");
        btn_nuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_nuevoActionPerformed(evt);
            }
        });

        btn_modificar.setText("Modificar");
        btn_modificar.setToolTipText("Modifica un registro");
        btn_modificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_modificarActionPerformed(evt);
            }
        });

        btn_borrar.setText("Borrar");
        btn_borrar.setToolTipText("Elimina un registro");
        btn_borrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_borrarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btn_grabar)
                    .addComponent(btn_primero))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btn_nuevo)
                    .addComponent(btn_anterior))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btn_modificar)
                    .addComponent(btn_siguiente))
                .addGap(18, 18, 18)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btn_borrar)
                    .addComponent(btn_ultimo))
                .addGap(48, 48, 48))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btn_primero)
                    .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(btn_siguiente)
                        .addComponent(btn_ultimo)
                        .addComponent(btn_anterior)))
                .addGap(18, 18, 18)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(btn_grabar)
                    .addComponent(btn_nuevo)
                    .addComponent(btn_modificar)
                    .addComponent(btn_borrar))
                .addContainerGap(18, Short.MAX_VALUE))
        );

        Tabla.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null},
                {null, null},
                {null, null}
            },
            new String [] {
                "Código", "Nombre de Barrio"
            }
        ));
        jScrollPane2.setViewportView(Tabla);

        jPanel4.setBackground(new java.awt.Color(0, 204, 153));

        bg_ordenar.add(rb_codigo);
        rb_codigo.setText("Código");

        bg_ordenar.add(rb_Nombre);
        rb_Nombre.setSelected(true);
        rb_Nombre.setText("Nombre");

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(rb_codigo)
                    .addComponent(rb_Nombre))
                .addContainerGap(25, Short.MAX_VALUE))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addGap(27, 27, 27)
                .addComponent(rb_codigo)
                .addGap(18, 18, 18)
                .addComponent(rb_Nombre)
                .addContainerGap(9, Short.MAX_VALUE))
        );

        jButton2.setText("Filtrar ");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(66, 66, 66)
                                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 202, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addGap(8, 8, 8))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 318, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jButton2)
                            .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, 318, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(0, 50, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(6, 6, 6)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton2))
                .addContainerGap(93, Short.MAX_VALUE))
        );

        setBounds(0, 0, 494, 551);
    }// </editor-fold>//GEN-END:initComponents

    private void btn_primeroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_primeroActionPerformed
        // TODO add your handling code here:
        try
        {
         conecta_barrio.resulset.first();
         mostrar_datos(); 
         btn_clicado = 1;
                        
        }
        catch (SQLException erro)
           {
                JOptionPane.showMessageDialog(null,"No es posible mostrar el primer registro "+erro);
           }
    }//GEN-LAST:event_btn_primeroActionPerformed

    private void btn_modificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_modificarActionPerformed
        // Codigo para actualizar
        try
        {
           String sqlUdpt = " update barrio set nombre = '"+ tf_nombre.getText()+"' where codigo = "+tf_codigo.getText();
                   conecta_barrio.statement.executeUpdate(sqlUdpt);
                    JOptionPane.showMessageDialog(null, sqlUdpt);
                   JOptionPane.showMessageDialog(null, "Modificción realizada con exito");
       //Actualizo el resulset porque hice una actualizacion
                conecta_barrio.resulset= conecta_barrio.statement.executeQuery("select * from barrio order by codigo");
                // actualiza_cb_ciudad();
                conecta_barrio.resulset.next();
                mostrar_datos();
        }
        catch (SQLException e)
        {
         JOptionPane.showMessageDialog(null,"Error al intentar grabar el registro  "+e);
        }
    }//GEN-LAST:event_btn_modificarActionPerformed

    private void btn_siguienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_siguienteActionPerformed
       
        try
        {
         conecta_barrio.resulset.next();
         mostrar_datos();
                   
        }
        catch (SQLException erro)
           {
                JOptionPane.showMessageDialog(null,"No es posible mostrar el siguiente registro "+erro);
           }
    }//GEN-LAST:event_btn_siguienteActionPerformed

    private void btn_ultimoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_ultimoActionPerformed
    
        try
        {
            conecta_barrio.resulset.last();
            mostrar_datos();
            btn_clicado = 4;
                        
        }
        catch (SQLException erro)
           {
                JOptionPane.showMessageDialog(null,"No es posible mostrar el último registro "+erro);
           }
    }//GEN-LAST:event_btn_ultimoActionPerformed

    private void btn_anteriorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_anteriorActionPerformed
        try
        {
            conecta_barrio.resulset.previous();
            mostrar_datos();
            btn_clicado = 3;
                       
        }
        catch (SQLException erro)
           {
                JOptionPane.showMessageDialog(null,"No es posible mostrar el registro anterior "+erro);
           }
    }//GEN-LAST:event_btn_anteriorActionPerformed

    private void btn_nuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_nuevoActionPerformed
    
      try
      {
   conecta_barrio.resulset.last();
   int cod = conecta_barrio.resulset.getInt("codigo")+1;
   tf_codigo.setText("");
   tf_nombre.setText("");
   
   
   tf_nombre.requestFocus();
   tf_codigo.setEditable(false);
   tf_codigo.setText(cod+"");
      }
      catch (SQLException e)
      {
        JOptionPane.showMessageDialog(null,"No es posible crear un nuevo registro  "+e);
      }
              
    }//GEN-LAST:event_btn_nuevoActionPerformed

    private void btn_grabarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_grabarActionPerformed
        // Codigo para grabar datos dentro de la BD
        try
        {
           String sqlInsert = "insert into barrio (codigo,nombre) values ("+
                   tf_codigo.getText()+",'"+ tf_nombre.getText()+"')";
                   conecta_barrio.statement.executeUpdate(sqlInsert);
                   JOptionPane.showMessageDialog(null, "Grabacion realizada con exito");
       //Actualizo el resulset
                conecta_barrio.resulset= conecta_barrio.statement.executeQuery("select * from barrio order by codigo");
                //actualiza_cb_ciudad();
                conecta_barrio.resulset.first();
                mostrar_datos();
        }
        catch (SQLException e)
        {
         JOptionPane.showMessageDialog(null,"Error al intentar grabar el registro  "+e);
        }
    }//GEN-LAST:event_btn_grabarActionPerformed

    private void btn_borrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_borrarActionPerformed
        // Codigo para eliminar un registro
        try
        {
           String sqlDel = "select * from barrio where codigo ="+tf_codigo.getText();
                   conecta_barrio.executeSQL(sqlDel);
                   conecta_barrio.resulset.first();
                   //me aseguro que el usurio no borre el registro sin querer
                   String nombre = "Desea Borrar el Barrio : "+ conecta_barrio.resulset.getString("nombre")+" ";
                   int opcion_elegida = JOptionPane.showConfirmDialog(null,nombre," Borrar ", JOptionPane.YES_NO_OPTION);
                   if (opcion_elegida == JOptionPane.YES_OPTION)
                   {
                       sqlDel = "DELETE FROM barrio where codigo ="+tf_codigo.getText();
                       int consigue_borrar = conecta_barrio.statement.executeUpdate(sqlDel);//0 o 1, este metodo pertenece a statement
                       if(consigue_borrar == 1)
                       {
                           JOptionPane.showMessageDialog(null,"Registro eliminado con éxito");
                           //actualizo mi resulset
                           conecta_barrio.executeSQL("select * from barrio order by codigo");
                           //actualiza_cb_ciudad();
                           conecta_barrio.resulset.first();//posiciona al primer registro
                           mostrar_datos();//llama al metodo mostrar datos
                       }
                   }
                   else
                   {
                       return; //si la opcion que recibe es distinta de 1 simplemente retorna y no pasa nada
                   }
             }
        catch (SQLException e)
        {
         JOptionPane.showMessageDialog(null,"Error al intentar borrar el registro  "+e);
        }
    }//GEN-LAST:event_btn_borrarActionPerformed

    private void btn_buscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_buscarActionPerformed
        // Codigo de busqueda
         try
        {
          conecta_barrio.resulset.first();
          String igual ="n";
          int tam_busqueda = tf_buscar.getText().length();
          while (igual == "n")
          {
              String buscar = conecta_barrio.resulset.getString("nombre").substring(0,tam_busqueda);
                if (buscar.equals(tf_buscar.getText()))
                {
                    igual = "s";
                }
                else
                {
                     conecta_barrio.resulset.next();
                }
          }       
       //
                tf_codigo.setText(conecta_barrio.resulset.getString("codigo"));
                mostrar_datos();
                cb_buscar.setSelectedItem(tf_nombre.getText());//asigno al combobox el nombre recuperado.
        }
        catch (SQLException e)
        {
         JOptionPane.showMessageDialog(null,"No se puede localizar el registro buscado  "+e);
        }
    }//GEN-LAST:event_btn_buscarActionPerformed

    private void btn_buscarCActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_buscarCActionPerformed
        // Codigo para buscar en un Combo Box
         try
        {
          conecta_barrio.resulset.first();
          String igual ="n";//inicio afirmando que el registro no esta disponible
          //int tam_busqueda = tf_buscar.getText().length();
          while ("n".equals(igual))
          {
              if (conecta_barrio.resulset.getString("nombre").equals(cb_buscar.getSelectedItem()))
                {
                    igual = "s";
                }
                else
                {
                     conecta_barrio.resulset.next();
                }
          }       
       //
                tf_codigo.setText(conecta_barrio.resulset.getString("codigo"));
                mostrar_datos();
        }
        catch (SQLException e)
        {
         JOptionPane.showMessageDialog(null,"No se puede localizar el registro buscado  "+e);
        }
    }//GEN-LAST:event_btn_buscarCActionPerformed

    private void cb_buscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cb_buscarActionPerformed
         // Codigo para buscar en un Combo Box sin usar el boton Buscar
         if (inicia_cbBuscar == 1)
         {
        try
        {
          conecta_barrio.resulset.first();
          String igual = "n";//inicio afirmando que el registro no esta disponible
         
          while ("n".equals(igual))
          {
              //String buscar = conecta_barrio.resulset.getString("nombre").substring(0,tam_busqueda);
                if (conecta_barrio.resulset.getString("nombre").equals(cb_buscar.getSelectedItem()))
                {
                    igual = "s";
                }
                else
                {
                     conecta_barrio.resulset.first();
                }
          }       
       //
                tf_codigo.setText(conecta_barrio.resulset.getString("codigo"));
                mostrar_datos();
        }
        catch (SQLException e)
        {
         JOptionPane.showMessageDialog(null,"No se puede localizar el registro buscado  "+e);
        }
       
    }//GEN-LAST:event_cb_buscarActionPerformed
     inicia_cbBuscar = 1;
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(registro_ciudad.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(registro_ciudad.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(registro_ciudad.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(registro_ciudad.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new registro_barrio().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTable Tabla;
    private javax.swing.ButtonGroup bg_ordenar;
    private javax.swing.JButton btn_anterior;
    private javax.swing.JButton btn_borrar;
    private java.awt.Button btn_buscar;
    private javax.swing.JButton btn_buscarC;
    private javax.swing.JButton btn_grabar;
    private javax.swing.JButton btn_modificar;
    private javax.swing.JButton btn_nuevo;
    private javax.swing.JButton btn_primero;
    private javax.swing.JButton btn_siguiente;
    private javax.swing.JButton btn_ultimo;
    private javax.swing.JComboBox cb_buscar;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JRadioButton rb_Nombre;
    private javax.swing.JRadioButton rb_codigo;
    private javax.swing.JTextField tf_buscar;
    private javax.swing.JTextField tf_codigo;
    private javax.swing.JTextField tf_nombre;
    // End of variables declaration//GEN-END:variables

public void mostrar_datos()
{
  try
        {
                      
            tf_codigo.setText(conecta_barrio.resulset.getString("codigo"));
            tf_nombre.setText(conecta_barrio.resulset.getString("nombre"));
           
            
        }
        catch (SQLException erro)
           {
               if(btn_clicado == 1)
               {
                   JOptionPane.showMessageDialog(null, "Usted ya esta en el primer registro");
               }
               else if (btn_clicado == 4)
               {
                JOptionPane.showMessageDialog(null, "Usted ya esta en el último registro");
               }
               else
                 
                JOptionPane.showMessageDialog(null,"No hay datos "+erro);
                btn_clicado = 0;
           }
}
 /*public void actualiza_cb_ciudad()
  {
       try
        {
            cb_buscar.removeAllItems();//elimina todos los items antes de actualizar
            conecta_barrio.executeSQL("select * from barrio order by codigo");
            while(conecta_barrio.resulset.next())//codigo buscar Combo BOX
            
             {
                  cb_buscar.addItem(conecta_barrio.resulset.getString("nombre"));
              }
                      
        }
        catch (SQLException erro)
           {
                JOptionPane.showMessageDialog(null,"No hay datos "+erro);
           }

}*/
 public void actualizaJtable()
{
    Tabla.getColumnModel().getColumn(0).setPreferredWidth(20);//defino el largo de la columna
    Tabla.getColumnModel().getColumn(1).setPreferredWidth(150);
    DefaultTableModel modelo = (DefaultTableModel)Tabla.getModel();
    modelo.setNumRows(0);//siempre que sea llamado el metodo limpiara la tabla

    try
  {
      while( conecta_barrio.resulset.next())
          //creo un vector donde cada una de las columnas tiene que estar conectada a un capo de la BD
          modelo.addRow(new Object[]{ conecta_barrio.resulset.getString("codigo"),conecta_barrio.resulset.getString("nombre")});
           conecta_barrio.resulset.first();
  }
catch(SQLException error)
        {
        JOptionPane.showMessageDialog(null, "Error al listar los datos");
        }

}
 public void ordenar_vista_rb(String orden)
 {
     ordenar = orden;
     conecta_barrio.executeSQL("select * fron barrio order by "+ordenar);
     actualizaJtable();
     //actualiza_cb_ciudad();
     try
     {
           conecta_barrio.resulset.first();
     }
     catch (SQLException error)
             {
              JOptionPane.showMessageDialog(null, "Error en la ordenación de los datos");
             }
 }
 
 
}




